
package com.jf.cloud.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.jf.cloud.api.delivery.dto.DeliveryOrderDTO;
import com.jf.cloud.api.delivery.feign.DeliveryFeignClient;
import com.jf.cloud.api.dto.PurchaseOrderUpdateDTO;
import com.jf.cloud.api.feign.SearchPurchaseOrderFeignClient;
import com.jf.cloud.api.leaf.feign.SegmentFeignClient;
import com.jf.cloud.api.multishop.feign.ShopDetailFeignClient;
import com.jf.cloud.api.multishop.vo.ShopDetailVO;
import com.jf.cloud.api.order.bo.EsPurchaseOrderBO;
import com.jf.cloud.api.order.constant.OrderStatus;
import com.jf.cloud.api.product.dto.SkuStockLockDTO;
import com.jf.cloud.api.product.feign.SkuStockLockFeignClient;
import com.jf.cloud.api.product.feign.SpuFeignClient;
import com.jf.cloud.api.supplier.bo.SupplierDetailBO;
import com.jf.cloud.api.supplier.feign.SupplierDetailFeignClient;
import com.jf.cloud.api.supplier.vo.SupplierApiDetailVO;
import com.jf.cloud.common.constant.DistributedIdKey;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.i18n.I18nMessage;
import com.jf.cloud.common.i18n.LanguageEnum;
import com.jf.cloud.common.order.bo.PayNotifyBO;
import com.jf.cloud.common.order.bo.RefundReductionStockBO;
import com.jf.cloud.common.order.constant.DeliveryType;
import com.jf.cloud.common.order.constant.OrderType;
import com.jf.cloud.common.product.constant.StockBillStatus;
import com.jf.cloud.common.product.constant.StockBillType;
import com.jf.cloud.common.product.constant.StockType;
import com.jf.cloud.common.product.vo.*;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.rocketmq.config.RocketMqConstant;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.common.util.Arith;
import com.jf.cloud.common.util.ExcelUtil;
import com.jf.cloud.common.util.LangUtil;
import com.jf.cloud.order.bo.mongo.MongoPurchaseOrderBO;
import com.jf.cloud.order.bo.mongo.MongoPurchaseOrderItemBO;
import com.jf.cloud.order.constant.PurchasesStatusEnum;
import com.jf.cloud.order.dto.PurchaseOrderDTO;
import com.jf.cloud.order.dto.PurchaseOrderItemDTO;
import com.jf.cloud.order.listener.PurchaseExcelListener;
import com.jf.cloud.order.manager.MongoPurchaseOrderManager;
import com.jf.cloud.order.mapper.PurchaseOrderItemMapper;
import com.jf.cloud.order.mapper.PurchaseOrderMapper;
import com.jf.cloud.order.model.*;
import com.jf.cloud.order.service.*;
import com.jf.cloud.order.vo.PurchaseOrderItemVO;
import com.jf.cloud.order.vo.PurchaseOrderVO;
import com.jf.cloud.order.vo.PurchaseSpuExcelVO;
import com.jf.cloud.order.vo.PurchaseSpuImportVO;
import io.seata.spring.annotation.GlobalTransactional;
import ma.glasnost.orika.MapperFacade;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 采购订单
 *
 * @author zz
 * @date 2022-06-22 17:12:02
 */
@Service
public class PurchaseOrderServiceImpl implements PurchaseOrderService {

    private static final Logger log = LoggerFactory.getLogger(PurchaseOrderServiceImpl.class);

    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;
    @Autowired
    private DeliveryFeignClient deliveryFeignClient;
    @Autowired
    private PurchaseOrderItemMapper purchaseOrderItemMapper;
    @Autowired
    private RocketMQTemplate orderRefundSuccessStockTemplate;
    @Autowired
    private PurchaseOrderLangService purchaseOrderLangService;
    @Autowired
    private PurchaseOrderItemService purchaseOrderItemService;
    @Autowired
    private MongoPurchaseOrderManager mongoPurchaseOrderManager;
    @Autowired
    private PurchaseOrderAddrService purchaseOrderAddrService;
    @Autowired
    private PurchaseOrderItemLangService purchaseOrderItemLangService;
    @Autowired
    private RocketMQTemplate orderNotifyServiceTemplate;
    @Autowired
    private MapperFacade mapperFacade;
    @Autowired
    private RocketMQTemplate stockBillLogTemplate;
    @Autowired
    private SupplierDetailFeignClient supplierDetailFeignClient;
    @Autowired
    private SpuFeignClient spuFeignClient;
    @Autowired
    private ShopDetailFeignClient shopDetailFeignClient;
    @Autowired
    private SkuStockLockFeignClient skuStockLockFeignClient;
    @Autowired
    private SegmentFeignClient segmentFeignClient;
    @Autowired
    private SearchPurchaseOrderFeignClient searchPurchaseOrderFeignClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional(rollbackFor = Exception.class)
    public void savePurchaseOrder(PurchaseOrderDTO purchaseOrderDTO) {
        // 检查库存
        this.checkStock(purchaseOrderDTO);
        ServerResponseEntity<ShopDetailVO> shopDetailResp = shopDetailFeignClient.getShopDetailByShopId(purchaseOrderDTO.getShopId());
        if (!shopDetailResp.isSuccess()) {
            throw new LuckException(shopDetailResp.getMsg());
        }
        List<SkuVO> skuList = new ArrayList<>();
        for (PurchaseOrderItemDTO purchaseOrderItem : purchaseOrderDTO.getPurchaseOrderItemList()) {
            SkuVO skuVO = new SkuVO();
            skuVO.setSkuId(purchaseOrderItem.getSkuId());
            skuVO.setSpuId(purchaseOrderItem.getSpuId());
            skuList.add(skuVO);
        }
        ServerResponseEntity<List<SpuAndSkuVO>> spuAndSkuResponse = spuFeignClient.listSpuAndSkuById(skuList,purchaseOrderDTO.getSupplierId());
        if (!spuAndSkuResponse.isSuccess()) {
            throw new LuckException(spuAndSkuResponse.getMsg());
        }
        List<SpuAndSkuVO> spuAndSkuList = spuAndSkuResponse.getData();
        Map<Long,SpuAndSkuVO> spuAndSkuMap = spuAndSkuList.stream().collect(Collectors.toMap(SpuAndSkuVO::getSkuId,spuAndSkuVO -> spuAndSkuVO));
        if (spuAndSkuList.size() <= 0) {
            throw new LuckException("yami.purchased.prod.not.exist.or.disabled");
        }
        double totalAmount = 0D;
        int totalStock = 0;
        List<PurchaseOrderItem> purchaseOrderItemList = new ArrayList<>();
        // 订单商品中文名称
        StringBuilder orderSpuNameCn = new StringBuilder(100);
        // 订单商品英文名称
        StringBuilder orderSpuNameEn = new StringBuilder(100);

        for (PurchaseOrderItemDTO purchaseOrderItemDTO : purchaseOrderDTO.getPurchaseOrderItemList()) {
            PurchaseOrderItem purchaseOrderItem = mapperFacade.map(purchaseOrderItemDTO, PurchaseOrderItem.class);
            SpuAndSkuVO spuAndSkuVO = spuAndSkuMap.get(purchaseOrderItem.getSkuId());
            SpuVO spu = spuAndSkuVO.getSpu();
            SkuVO sku = spuAndSkuVO.getSku();
            purchaseOrderItem.setStatus(PurchasesStatusEnum.UNPAY.value());
            purchaseOrderItem.setActualStock(0);
            purchaseOrderItem.setSpuId(spu.getSpuId());
            purchaseOrderItem.setSkuId(sku.getSkuId());
            purchaseOrderItem.setSpuCode(spu.getSpuCode());
            purchaseOrderItem.setPartyCode(sku.getPartyCode());
            purchaseOrderItem.setPic(StrUtil.isNotBlank(sku.getImgUrl()) ? sku.getImgUrl() : spu.getMainImgUrl());
            purchaseOrderItem.setPurchaseOrderId(purchaseOrderDTO.getPurchaseOrderId());
            purchaseOrderItem.setPurchasePrice(sku.getPriceFee());
            purchaseOrderItem.setPurchaseAmount(sku.getPriceFee() * purchaseOrderItem.getPurchaseStock());
            purchaseOrderItem.setBeDeliveredNum(purchaseOrderItem.getPurchaseStock());
            purchaseOrderItem.setPurchaseOrderItemLangList(getOrderItemLangList(sku.getSkuLangList(),spu.getSpuLangList(),orderSpuNameCn,orderSpuNameEn));
            purchaseOrderItemList.add(purchaseOrderItem);
            totalAmount = Arith.add(totalAmount, purchaseOrderItem.getPurchaseAmount());
            totalStock += purchaseOrderItem.getPurchaseStock();
        }

        // 1.保存订单地址
        if (Objects.isNull(shopDetailResp.getData())) {
            // 请填写收货地址
            throw new LuckException("请先去填写店铺收货地址");
        }
        ShopDetailVO shopDetailVO = shopDetailResp.getData();
        PurchaseOrderAddr purchaseOrderAddr = mapperFacade.map(shopDetailVO, PurchaseOrderAddr.class);
        purchaseOrderAddr.setPurchaseOrderAddrId(purchaseOrderDTO.getAddrId());
        purchaseOrderAddr.setConsignee(shopDetailVO.getContactName());
        purchaseOrderAddr.setAddr(shopDetailVO.getDetailAddress());
        purchaseOrderAddr.setMobile(shopDetailVO.getContactPhone());
        purchaseOrderAddr.setPurchaseOrderAddrId(purchaseOrderDTO.getAddrId());
        purchaseOrderAddrService.save(purchaseOrderAddr);

        // 2.保存订单信息
        Date date = new Date();
        purchaseOrderDTO.setCreateTime(date);
        purchaseOrderDTO.setUpdateTime(date);
        purchaseOrderDTO.setTotalAmount(totalAmount);
        purchaseOrderDTO.setTotalStock(totalStock);
        purchaseOrderDTO.setActualTotalStock(0);
        purchaseOrderDTO.setStatus(PurchasesStatusEnum.UNPAY.value());

        PurchaseOrder purchaseOrder = mapperFacade.map(purchaseOrderDTO, PurchaseOrder.class);
        // 1.设置配送方式
        purchaseOrder.setDeliveryType(DeliveryType.DELIVERY.value());
        purchaseOrder.setPurchaseOrderAddrId(purchaseOrderAddr.getPurchaseOrderAddrId());
        purchaseOrderMapper.save(purchaseOrder);
        // 2.处理下订单商品语言
        orderSpuNameCn = new StringBuilder(orderSpuNameCn.subSequence(0, Math.min(orderSpuNameCn.length() - 1, 100)));
        if (orderSpuNameCn.lastIndexOf(StrUtil.COMMA) == orderSpuNameCn.length() - 1) {
            orderSpuNameCn.deleteCharAt(orderSpuNameCn.length() - 1);
        }
        if(StrUtil.isNotBlank(orderSpuNameEn)) {
            orderSpuNameEn = new StringBuilder(orderSpuNameEn.subSequence(0, Math.min(orderSpuNameEn.length() - 1, 100)));
            if (orderSpuNameEn.lastIndexOf(StrUtil.COMMA) == orderSpuNameEn.length() - 1) {
                orderSpuNameEn.deleteCharAt(orderSpuNameEn.length() - 1);
            }
        }
        purchaseOrderLangService.saveBatch(orderSpuNameCn,orderSpuNameEn,purchaseOrder.getPurchaseOrderId());

        purchaseOrderItemMapper.saveBatch(purchaseOrderItemList);

        // 3.保存订单商品名称
        purchaseOrderItemLangService.saveOrderItemLang(purchaseOrderItemList);

        // 4.减少库存,发送消息，订单支付成功 通知库存扣减
        PayNotifyBO message = new PayNotifyBO();
        message.setOrderIds(Collections.singletonList(purchaseOrder.getPurchaseOrderId()));
        message.setOrderType(OrderType.ORDINARY.value());
        // 限定采购订单，方便该通知只能执行库存扣减
        message.setPurchaseOrder(true);
        SendStatus sendStatus = orderNotifyServiceTemplate.syncSend(RocketMqConstant.ORDER_NOTIFY_SERVICE_TOPIC, new GenericMessage<>(message)).getSendStatus();
        if (!Objects.equals(sendStatus,SendStatus.SEND_OK)) {
            throw new LuckException(ResponseEnum.EXCEPTION);
        }

        // 5.采购的商品未导入时自动导入供应商商品
        voluntarilyImportSupplierSpu(purchaseOrderDTO);
    }


    /**
     * 采购订单中商品未导入自动导入
     * @param purchaseOrderDT
     */
    private void voluntarilyImportSupplierSpu(PurchaseOrderDTO purchaseOrderDT){
        List<SpuVO> spuVOS = new ArrayList<>();
        for (PurchaseOrderItemDTO purchaseOrderItemDTO : purchaseOrderDT.getPurchaseOrderItemList()) {
            SpuVO spuVO = new SpuVO();
            spuVO.setShopId(purchaseOrderDT.getShopId());
            spuVO.setSupplierSpuId(purchaseOrderItemDTO.getSpuId());
            spuVOS.add(spuVO);
        }
        Integer sysType = AuthUserContext.get().getSysType();
        ServerResponseEntity<Void> voidServerResponseEntity = spuFeignClient.voluntarilyImportSupplierSpu(spuVOS, sysType,
                AuthUserContext.get().getUserId());
        if (!voidServerResponseEntity.isSuccess()) {
            throw new LuckException(voidServerResponseEntity.getMsg());
        }
    }
    /**
     * 获取订单项的国际化信息
     *
     * @param skuLangList 规格语言信息
     * @param spuLangList 商品语言信息
     * @param orderSpuNameCn
     * @param orderSpuNameCn
     * @return 订单项的国际化信息列表
     */
    private List<PurchaseOrderItemLang> getOrderItemLangList(List<SkuLangVO> skuLangList, List<SpuLangVO> spuLangList,
                                                             StringBuilder orderSpuNameCn,StringBuilder orderSpuNameEn) {
        List<PurchaseOrderItemLang> orderItemLangList = new ArrayList<>();
        Map<Integer, String> spuNameMap = spuLangList.stream()
                .filter(orderSpuLangVO -> StrUtil.isNotBlank(orderSpuLangVO.getSpuName()))
                .collect(Collectors.toMap(SpuLangVO::getLang, SpuLangVO::getSpuName));
        Map<Integer, String> skuNameMap = skuLangList.stream()
                .filter(orderSkuLangVO -> StrUtil.isNotBlank(orderSkuLangVO.getSkuName()))
                .collect(Collectors.toMap(SkuLangVO::getLang, SkuLangVO::getSkuName));

        for (LanguageEnum value : LanguageEnum.values()) {
            Integer lang = value.getLang();
            if (!spuNameMap.containsKey(lang) && !skuNameMap.containsKey(lang)) {
                continue;
            }
            PurchaseOrderItemLang orderItemLang = new PurchaseOrderItemLang();
            orderItemLang.setLang(value.getLang());
            orderItemLang.setSkuName(LangUtil.getLangValue(skuNameMap, lang));
            orderItemLang.setSpuName(LangUtil.getLangValue(spuNameMap, lang));
            orderItemLangList.add(orderItemLang);
            if(Objects.equals(value,LanguageEnum.LANGUAGE_ZH_CN)){
                orderSpuNameCn.append(orderItemLang.getSpuName()).append(StrUtil.COMMA);
            }else{
                orderSpuNameEn.append(orderItemLang.getSpuName()).append(StrUtil.COMMA);
            }
        }
        return orderItemLangList;
    }


    @Override
    public PurchaseOrderVO info(Long purchaseOrderId, Long supplierId) {
        PurchaseOrderVO purchaseOrder = purchaseOrderMapper.info(purchaseOrderId,supplierId, I18nMessage.getLang());
        if (Objects.isNull(purchaseOrder)) {
            throw new LuckException("采购订单不存在");
        }
        ServerResponseEntity<ShopDetailVO> shopResp = shopDetailFeignClient.getShopDetailByShopId(purchaseOrder.getShopId());
        if (!shopResp.isSuccess()) {
            throw new LuckException(shopResp.getMsg());
        }
        purchaseOrder.setShopName(shopResp.getData().getMerchantName());
        ServerResponseEntity<SupplierDetailBO> supplierResp = supplierDetailFeignClient.getSupplierBySupplierId(purchaseOrder.getSupplierId());
        if (!supplierResp.isSuccess()) {
            throw new LuckException(supplierResp.getMsg());
        }
        purchaseOrder.setSupplierName(supplierResp.getData().getSupplierName());
//        if (CollUtil.isNotEmpty(purchaseOrder.getPurchaseOrderItemList())) {
//            purchaseOrderItemService.loadProdAndSkuInfo(purchaseOrder.getPurchaseProds());
//        }
        orderLangHandle(purchaseOrder);
        return purchaseOrder;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional(rollbackFor = Exception.class)
    public void delivery(DeliveryOrderDTO deliveryOrderParam) {
        PurchaseOrderVO purchaseOrderVO = purchaseOrderMapper.info(deliveryOrderParam.getOrderId(), AuthUserContext.get().getTenantId(), I18nMessage.getLang());
        deliveryOrderParam.setUserId(purchaseOrderVO.getShopId());


        purchaseOrderItemService.updateByDeliveries(deliveryOrderParam.getSelectOrderItems(), deliveryOrderParam.getDeliveryType());
        // 算下未发货商品数量
        int unDeliveryNum = purchaseOrderItemService.countUnDeliveryNumByOrderId(deliveryOrderParam.getOrderId());
//        if (Objects.equals(deliveryOrderParam.getDeliveryType(), DeliveryType.DELIVERY.value())) {
//            StringBuilder sb = new StringBuilder();
//            for (DeliveryOrderItemDTO selectOrderItem : deliveryOrderParam.getSelectOrderItems()) {
//                sb.append(selectOrderItem.getSpuName()).append(StrUtil.COMMA);
//            }
//            sb.deleteCharAt(sb.length() - 1);
//            // 获取订单发货信息
//            // TODO 消息推送-发货提醒,通知其他服务
//        }
        //修改为发货状态
        if (Objects.equals(unDeliveryNum, 0)) {
            Date date = new Date();
            PurchaseOrder order = new PurchaseOrder();
            order.setPurchaseOrderId(deliveryOrderParam.getOrderId());
            order.setStatus(PurchasesStatusEnum.DELIVERY.value());
            order.setUpdateTime(date);
            order.setDeliveryTime(date);
            //判断是无需物流还是快递发货,如果是无需快递，则判断该订单是否包含有物流的项，若有物流则配送类型为快递配送，没有物流则不变
            if (purchaseOrderItemService.getDevTypeByOrderId(deliveryOrderParam.getOrderId())) {
                order.setDeliveryType(DeliveryType.DELIVERY.value());
            } else {
                order.setDeliveryType(deliveryOrderParam.getDeliveryType());
            }
            purchaseOrderMapper.updateByPurchaseId(order);
            purchaseOrderItemService.updateStatusByPurchaseOrderId(PurchasesStatusEnum.DELIVERY.value(), order.getPurchaseOrderId());
            updatePurchaseOrderStatus(order);
        }
        // 先更改订单状态，再保存包裹信息
        ServerResponseEntity<Void> resp = deliveryFeignClient.saveDeliveryInfo(deliveryOrderParam);
        if (resp.isFail()) {
            throw new LuckException(resp.getMsg());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePayVoucher(PurchaseOrderDTO purchaseOrder) {
        PurchaseOrder purchaseOrderDb = purchaseOrderMapper.getByPurchaseOrderId(purchaseOrder.getPurchaseOrderId());
        if (!Objects.equals(purchaseOrderDb.getShopId(), purchaseOrderDb.getShopId())) {
            throw new LuckException(ResponseEnum.UNAUTHORIZED);
        }
        if (!Objects.equals(purchaseOrderDb.getStatus(), PurchasesStatusEnum.UNPAY.value())) {
            throw new LuckException("此订单状态已改变，不能进行此操作");
        }
        purchaseOrderDb.setVoucherImgUrls(purchaseOrder.getVoucherImgUrls());
        purchaseOrderDb.setStatus(PurchasesStatusEnum.WAITAUDIT.value());
        purchaseOrderMapper.updateByPurchaseId(purchaseOrderDb);
        purchaseOrderItemService.updateStatusByPurchaseOrderId(purchaseOrderDb.getStatus(), purchaseOrderDb.getPurchaseOrderId());
        updatePurchaseOrderStatus(purchaseOrderDb);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditVoucher(PurchaseOrderDTO purchaseOrder) {
        PurchaseOrder purchaseOrderDb = purchaseOrderMapper.getByPurchaseOrderId(purchaseOrder.getPurchaseOrderId());
        if (!Objects.equals(purchaseOrder.getSupplierId(), purchaseOrderDb.getSupplierId())) {
            throw new LuckException(ResponseEnum.UNAUTHORIZED);
        }
        if (!Objects.equals(purchaseOrderDb.getStatus(), PurchasesStatusEnum.WAITAUDIT.value())) {
            throw new LuckException("此订单状态已改变，不能进行此操作");
        }
        // 1-审核通过
        if (Objects.equals(purchaseOrder.getStatus(), 1)) {
            purchaseOrderDb.setStatus(PurchasesStatusEnum.WAIT_STOCK.value());
            // 0-审核不通过
        } else if (Objects.equals(purchaseOrder.getStatus(), 0)) {
            purchaseOrderDb.setStatus(PurchasesStatusEnum.VOIDED.value());
            reductionStock(purchaseOrderMapper.info(purchaseOrderDb.getPurchaseOrderId(), purchaseOrderDb.getSupplierId(), I18nMessage.getLang()));
        }else {
            return;
        }
        purchaseOrderMapper.updateByPurchaseId(purchaseOrderDb);
        purchaseOrderItemService.updateStatusByPurchaseOrderId(purchaseOrderDb.getStatus(), purchaseOrderDb.getPurchaseOrderId());
        updatePurchaseOrderStatus(purchaseOrderDb);
    }

    /**
     * 更新供应商订单时，手动更新状态
     * 更新状态失败后续还有canal监听进行更新，优先原本功能的执行，所以不能抛出异常
     * @param order
     */
    private void updatePurchaseOrderStatus(PurchaseOrder order) {
        try {
            searchPurchaseOrderFeignClient.updatePurchaseOrderStatus(new PurchaseOrderUpdateDTO(order.getPurchaseOrderId(), order.getStatus()));
        } catch (Exception e) {
            log.error("供应商订单更新状态失败：{}", e);
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void inbound(PurchaseOrderDTO purchaseOrderDTO) {
        PurchaseOrderVO purchaseOrderDb = purchaseOrderMapper.info(purchaseOrderDTO.getPurchaseOrderId(), null, I18nMessage.getLang());
        if (!Objects.equals(purchaseOrderDTO.getShopId(), purchaseOrderDb.getShopId())) {
            throw new LuckException(ResponseEnum.UNAUTHORIZED);
        }
        if (Objects.equals(purchaseOrderDb.getStatus(), PurchasesStatusEnum.VOIDED.value())) {
            throw new LuckException("此订单已作废");
        }
        if (Objects.equals(purchaseOrderDb.getStatus(), PurchasesStatusEnum.COMPLETION.value())) {
            throw new LuckException("此订单已完成");
        }
        purchaseOrderDb.setDeliverTime(new Date());
        List<PurchaseOrderItemVO> purchaseOrderItemListDb = purchaseOrderDb.getPurchaseOrderItemList();
        // 转换成map
        Map<Long, PurchaseOrderItemDTO> orderItemMap = purchaseOrderDTO.getPurchaseOrderItemList().stream().collect(Collectors.toMap(PurchaseOrderItemDTO::getPurchaseItemId, p -> p));
        purchaseOrderDb.setRemark(purchaseOrderDTO.getRemark());
        Iterator<PurchaseOrderItemVO> iterator = purchaseOrderItemListDb.iterator();
        Integer actualTotalStock = 0;
        List<StockBillLogItemVO> stockBillLogItems = new ArrayList<>();
        boolean complete = true;
        while (iterator.hasNext()) {
            PurchaseOrderItemVO purchaseProdDb = iterator.next();
            if (!orderItemMap.containsKey(purchaseProdDb.getPurchaseItemId()) || Objects.equals(purchaseProdDb.getStatus(), 0)) {
                actualTotalStock += purchaseProdDb.getActualStock();
                iterator.remove();
                if (purchaseProdDb.getActualStock() < purchaseProdDb.getPurchaseStock() && !Objects.equals(purchaseProdDb.getStatus(), 0)) {
                    complete = false;
                }
                continue;
            }
            PurchaseOrderItemDTO purchaseOrderItemVO = orderItemMap.get(purchaseProdDb.getPurchaseItemId());
            if (!Objects.equals(purchaseProdDb.getStatus(), PurchasesStatusEnum.DELIVERY.value()) && !Objects.equals(purchaseProdDb.getStatus(), PurchasesStatusEnum.PARTIALLY_STOCK.value())) {
                continue;
            }
            Integer actualStock = purchaseProdDb.getActualStock() + purchaseOrderItemVO.getActualStock();
//            if(actualStock > purchaseProdDb.getPurchaseStock()){
//                throw new LuckException("入库数量错误，请刷新后再试");
//            }
            if (actualStock > 0 && purchaseProdDb.getPurchaseStock() > actualStock) {
                purchaseProdDb.setStatus(PurchasesStatusEnum.PARTIALLY_STOCK.value());
            }
            if (Objects.equals(purchaseProdDb.getPurchaseStock(), actualStock)) {
                purchaseProdDb.setStatus(PurchasesStatusEnum.COMPLETION.value());
            }
            Integer changeStock = actualStock - purchaseProdDb.getActualStock();
            if (complete && actualStock < purchaseOrderItemVO.getPurchaseStock()) {
                complete = false;
            }
            if (actualStock - purchaseProdDb.getActualStock() <= 0) {
                continue;
            }
            stockBillLogItems.add(loadStockBillLogItem(purchaseOrderItemVO, changeStock));
            purchaseProdDb.setActualStock(actualStock);
            actualTotalStock += purchaseProdDb.getActualStock();
        }
        // 部分入库
        if (actualTotalStock > 0 && Objects.equals(purchaseOrderDb.getStatus(), PurchasesStatusEnum.DELIVERY.value())) {
            purchaseOrderDb.setStatus(PurchasesStatusEnum.PARTIALLY_STOCK.value());
        }
        // 已完成
        if (complete) {
            purchaseOrderDb.setStatus(PurchasesStatusEnum.COMPLETION.value());
        }
        if (CollUtil.isNotEmpty(stockBillLogItems)) {
            StockBillLogVO stockBillLog = loadStockBillLog(purchaseOrderDb, stockBillLogItems);
            // 发送事件进行添加商品库存记录
            SendStatus sendStockStatus = stockBillLogTemplate.syncSend(RocketMqConstant.STOCK_BILL_LOG_TOPIC, new GenericMessage<>(stockBillLog)).getSendStatus();
            if (!Objects.equals(sendStockStatus,SendStatus.SEND_OK)) {
                throw new LuckException(ResponseEnum.EXCEPTION);
            }
        }
        PurchaseOrder purchaseOrder = mapperFacade.map(purchaseOrderDb, PurchaseOrder.class);
        purchaseOrder.setActualTotalStock(actualTotalStock);
        purchaseOrderMapper.updateByPurchaseId(purchaseOrder);
        List<PurchaseOrderItem> purchaseOrderItems = mapperFacade.mapAsList(purchaseOrderItemListDb, PurchaseOrderItem.class);
        purchaseOrderItemService.updateBatchById(purchaseOrderItems);
        updatePurchaseOrderStatus(purchaseOrder);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void nullify(Long shopId, Long purchaseOrderId) {
        PurchaseOrderVO purchaseOrderVO = purchaseOrderMapper.info(purchaseOrderId,null, I18nMessage.getLang());
        if (!Objects.equals(purchaseOrderVO.getShopId(), shopId)) {
            throw new LuckException(ResponseEnum.UNAUTHORIZED);
        }
//        if (!Objects.equals(purchaseOrderVO.getStatus(), 1)) {
//            throw new LuckException("数据已过期，请刷新页面");
//        }
        Integer status = purchaseOrderVO.getStatus();
        if (Objects.equals(purchaseOrderVO.getStatus(), PurchasesStatusEnum.VOIDED.value())) {
            throw new LuckException("此订单已作废");
        }
        purchaseOrderVO.setStatus(PurchasesStatusEnum.VOIDED.value());
        PurchaseOrder purchaseOrder = mapperFacade.map(purchaseOrderVO, PurchaseOrder.class);
        purchaseOrderMapper.updateByPurchaseId(purchaseOrder);
        purchaseOrderItemMapper.updateStatusByPurchaseOrderId(Collections.singletonList(purchaseOrder.getPurchaseOrderId()), PurchasesStatusEnum.VOIDED.value());
        if (Objects.equals(status, PurchasesStatusEnum.COMPLETION.value())) {
            return;
        }
        // 还原库存
        reductionStock(purchaseOrderVO);
        updatePurchaseOrderStatus(purchaseOrder);
    }

    private void reductionStock(PurchaseOrderVO purchaseOrderVO) {
        // 订单待发货或待成团订单超时，结果就被取消了，还原库存
        if (Objects.equals(purchaseOrderVO.getStatus(), OrderStatus.PAYED.value()) || Objects.equals(purchaseOrderVO.getStatus(), OrderStatus.WAIT_GROUP.value())) {
            return;
        }
        List<RefundReductionStockBO> refundReductionStocks;
        if (CollUtil.isEmpty(purchaseOrderVO.getPurchaseOrderItemList())){
            log.info("采购单商品为空，采购单id：{}",purchaseOrderVO.getPurchaseOrderId());
            return;
        }
        refundReductionStocks = purchaseOrderVO.getPurchaseOrderItemList().stream().map(orderItem -> {
            // 部分入库后还原库存
            int remainStock = orderItem.getPurchaseStock() - orderItem.getActualStock();
            if (remainStock == 0) {
                return null;
            }
            RefundReductionStockBO refundReductionStockBO = new RefundReductionStockBO();
            refundReductionStockBO.setCount(remainStock);
            refundReductionStockBO.setSkuId(orderItem.getSkuId());
            refundReductionStockBO.setSpuId(orderItem.getSpuId());
            refundReductionStockBO.setOrderId(purchaseOrderVO.getPurchaseOrderId());
            refundReductionStockBO.setShopId(purchaseOrderVO.getShopId());
            refundReductionStockBO.setSupplierProd(1);
            return refundReductionStockBO;
        }).filter(Objects::nonNull).collect(Collectors.toList());

        if (CollUtil.isEmpty(refundReductionStocks)) {
            return;
        }
        // 通知还原库存
        SendStatus sendStatus = orderRefundSuccessStockTemplate.syncSend(RocketMqConstant.ORDER_REFUND_SUCCESS_STOCK_TOPIC, new GenericMessage<>(refundReductionStocks)).getSendStatus();

        if (!Objects.equals(sendStatus, SendStatus.SEND_OK)) {
            throw new LuckException(ResponseEnum.EXCEPTION);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void complete(Long shopId, Long purchaseOrderId) {
        PurchaseOrderVO purchaseOrderVO = purchaseOrderMapper.info(purchaseOrderId,null, I18nMessage.getLang());
        if (!Objects.equals(purchaseOrderVO.getShopId(), shopId)) {
            throw new LuckException(ResponseEnum.UNAUTHORIZED);
        }
        if (!Objects.equals(purchaseOrderVO.getStatus(), PurchasesStatusEnum.PARTIALLY_STOCK.value())) {
            throw new LuckException("数据已过期，请刷新页面");
        }
        purchaseOrderVO.setStatus(PurchasesStatusEnum.COMPLETION.value());
        PurchaseOrder purchaseOrder = mapperFacade.map(purchaseOrderVO, PurchaseOrder.class);
        purchaseOrderMapper.updateByPurchaseId(purchaseOrder);
        purchaseOrderItemMapper.updateStatusByPurchaseOrderId(Collections.singletonList(purchaseOrder.getPurchaseOrderId()), PurchasesStatusEnum.COMPLETION.value());
        // 还原库存
        reductionStock(purchaseOrderVO);
        updatePurchaseOrderStatus(purchaseOrder);
    }

    @Override
    public void downloadModel(HttpServletResponse response) {
        List<PurchaseSpuExcelVO> list = new ArrayList<>();
        list.add(new PurchaseSpuExcelVO());
        Map<Integer, String[]> map = new HashMap<>(8);
        ExcelWriter excelWriter = null;
        try {
            // 先执行合并策略
            ExcelWriterBuilder excelWriterMerge = ExcelUtil.getExcelWriterMerge(response, PurchaseSpuExcelVO.EXCEL_NAME, PurchaseSpuExcelVO.MERGE_ROW_INDEX, PurchaseSpuExcelVO.MERGE_COLUMN_INDEX);
            // useDefaultStyle false 不需要默认的头部加粗/自动换行样式
            excelWriter = ExcelUtil.getExcelModel(excelWriterMerge, map, 1).useDefaultStyle(false).build();
            // 业务代码
            if (CollUtil.isNotEmpty(list)) {
                // 进行写入操作
                WriteSheet sheetWriter = EasyExcel.writerSheet(PurchaseSpuExcelVO.SHEET_NAME).head(PurchaseSpuExcelVO.class).build();
                excelWriter.write(list, sheetWriter);
            }
        } catch (Exception e) {
            log.error("导出用户信息模板excel失败", e);
        } finally {
            // 千万别忘记finish 会帮忙关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }

    @Override
    public PurchaseSpuImportVO parseFile(MultipartFile file, Long shopId) {
        Map<String, List<String>> errorMap = new HashMap<>(16);
        List<PurchaseSpuExcelVO> purchaseSpuExcelVOS = new ArrayList<>();
        PurchaseExcelListener purchaseExcelListener = new PurchaseExcelListener(errorMap, purchaseSpuExcelVOS);
        try {
            EasyExcel.read(file.getInputStream(), PurchaseSpuExcelVO.class, purchaseExcelListener).sheet().doRead();
        } catch (IOException e) {
            throw new LuckException(e.getMessage());
        }
        if(CollectionUtil.isEmpty(purchaseSpuExcelVOS)){
            throw new LuckException("导入数据为空，请检查下文件");
        }
        // 数据处理，并查询采购商品的信息
        List<String> partyCodes = new ArrayList<>();
        Map<String, Integer> purchaseStockMap = new HashMap<>(16);
        for (PurchaseSpuExcelVO purchaseSpuExcelVO : purchaseSpuExcelVOS) {
            partyCodes.add(purchaseSpuExcelVO.getPartyCode());
            purchaseStockMap.put(purchaseSpuExcelVO.getPartyCode(), purchaseSpuExcelVO.getPurchaseStock());
        }
        ServerResponseEntity<List<PurchaseSpuVO>> listServerResponseEntity = spuFeignClient.listPurchaseSpuByPartyCodeList(partyCodes, shopId);
        if(!listServerResponseEntity.isSuccess()){
            throw new LuckException(listServerResponseEntity.getMsg());
        }
        List<PurchaseSpuVO> purchaseSpuList = listServerResponseEntity.getData();
        // 此商家可采购的供应商Id
        ServerResponseEntity<List<Long>> supplierIdsResponse = supplierDetailFeignClient.listSupplierIdByShopIdAndSupplierName(shopId, null);
        if(supplierIdsResponse.isFail()){
            throw new LuckException(supplierIdsResponse.getMsg());
        }
        List<Long> limitSupplierIdList = supplierIdsResponse.getData();
        HashSet<Long> limitSupplierIdSet = new HashSet<>(limitSupplierIdList);
        // 过滤无法采购的供应商商品
        Iterator<PurchaseSpuVO> purchaseSpuIterator = purchaseSpuList.iterator();
        while (purchaseSpuIterator.hasNext()) {
            PurchaseSpuVO purchaseSpuVO = purchaseSpuIterator.next();
            if (!limitSupplierIdSet.contains(purchaseSpuVO.getSupplierId())) {
                purchaseSpuIterator.remove();
            }
        }
        // 查询供应商信息
        List<Long> supplierIds = purchaseSpuList.stream().map(PurchaseSpuVO::getSupplierId).collect(Collectors.toList());
        ServerResponseEntity<List<SupplierApiDetailVO>> supplierDetailResponseEntity = supplierDetailFeignClient.listBySupplierIds(supplierIds);
        if(supplierDetailResponseEntity.isFail()){
            throw new LuckException(supplierDetailResponseEntity.getMsg());
        }
        Map<Long, String> supplierNameMap = supplierDetailResponseEntity.getData().stream().collect(Collectors.toMap(SupplierApiDetailVO::getSupplierId, SupplierApiDetailVO::getSupplierName));
        for (PurchaseSpuVO purchaseSpuVO : purchaseSpuList) {
            purchaseSpuVO.setPurchaseStock(purchaseStockMap.get(purchaseSpuVO.getPartyCode()));
            purchaseSpuVO.setSupplierName(supplierNameMap.get(purchaseSpuVO.getSupplierId()));
        }
        PurchaseSpuImportVO purchaseSpuImportVO = new PurchaseSpuImportVO();
        purchaseSpuImportVO.setPurchaseSpuList(purchaseSpuList);
        String tips = "检查到" + purchaseSpuExcelVOS.size() + "条商品信息，成功导入" +
                (purchaseSpuList.size()) + "条商品信息！错误" + (purchaseSpuExcelVOS.size() - purchaseSpuList.size()) + "条商品信息!";
        purchaseSpuImportVO.setTips(tips);
        return purchaseSpuImportVO;
    }

    @Override
    public EsPurchaseOrderBO saveMongoAndGetEsInfo(Long purchaseOrderId) {
        MongoPurchaseOrderBO pruchaseOrder = purchaseOrderMapper.getMongoPruchaseOrderInfo(purchaseOrderId);
        loadMongoPurchaseOrderBo(pruchaseOrder);
        mongoPurchaseOrderManager.save(pruchaseOrder);
        return mapperFacade.map(pruchaseOrder, EsPurchaseOrderBO.class);
    }
    private void loadMongoPurchaseOrderBo(MongoPurchaseOrderBO purchaseOrderBO) {
        for (MongoPurchaseOrderItemBO purchaseOrderItem : purchaseOrderBO.getPurchaseOrderItems()) {
            for (PurchaseOrderItemLang purchaseOrderItemLang : purchaseOrderItem.getPurchaseOrderItemLangs()) {
                if (Objects.equals(purchaseOrderItemLang.getLang(), LanguageEnum.LANGUAGE_ZH_CN.getLang())) {
                    purchaseOrderItem.setSpuNameZh(purchaseOrderItemLang.getSpuName());
                    purchaseOrderItem.setSkuNameZh(purchaseOrderItemLang.getSkuName());
                } else if (Objects.equals(purchaseOrderItemLang.getLang(), LanguageEnum.LANGUAGE_EN.getLang())) {
                    purchaseOrderItem.setSpuNameEn(purchaseOrderItemLang.getSpuName());
                    purchaseOrderItem.setSkuNameEn(purchaseOrderItemLang.getSkuName());
                }
            }
            purchaseOrderItem.setPurchaseOrderItemLangs(null);
        }
        for (PurchaseOrderLang purchaseOrderLang : purchaseOrderBO.getPurchaseOrderLangs()) {
            if (Objects.equals(purchaseOrderLang.getLang(), LanguageEnum.LANGUAGE_ZH_CN.getLang())) {
                purchaseOrderBO.setSpuNameZh(purchaseOrderLang.getSpuName());
            } else if (Objects.equals(purchaseOrderLang.getLang(), LanguageEnum.LANGUAGE_EN.getLang())) {
                purchaseOrderBO.setSpuNameEn(purchaseOrderLang.getSpuName());
            }
        }
        purchaseOrderBO.setPurchaseOrderLangs(null);
        ServerResponseEntity<ShopDetailVO> shopDetailResponseEntity = shopDetailFeignClient.getShopDetailByShopId(purchaseOrderBO.getShopId());
        if (shopDetailResponseEntity.isFail()) {
            throw new LuckException(shopDetailResponseEntity.getMsg());
        }
        purchaseOrderBO.setShopName(shopDetailResponseEntity.getData().getShopName());

        ServerResponseEntity<SupplierDetailBO> supplierResponseEntity = supplierDetailFeignClient.getSupplierBySupplierId(purchaseOrderBO.getSupplierId());
        if (supplierResponseEntity.isFail()) {
            throw new LuckException(supplierResponseEntity.getMsg());
        }
        purchaseOrderBO.setSupplierName(supplierResponseEntity.getData().getSupplierName());
    }

    /**
     * 检查采购商品库存
     * @param purchaseOrderDTO
     */
    private void checkStock(PurchaseOrderDTO purchaseOrderDTO) {
        List<SkuStockLockDTO> skuStockLocks = new ArrayList<>();
        List<PurchaseOrderItemDTO> purchaseOrderItemList = purchaseOrderDTO.getPurchaseOrderItemList();
        purchaseOrderItemList.forEach(purchaseOrderItem -> skuStockLocks.add(new SkuStockLockDTO(0L, purchaseOrderItem.getSpuId(), purchaseOrderItem.getSkuId(), purchaseOrderDTO.getPurchaseOrderId(), purchaseOrderItem.getPurchaseStock(),-1,null)));
        // 锁定库存
        ServerResponseEntity<?> lockStockResponse = skuStockLockFeignClient.lock(skuStockLocks);
        // 提示具体哪个商品库存不足
        if (Objects.equals(ResponseEnum.NOT_STOCK.value(), lockStockResponse.getCode())) {
            for (PurchaseOrderItemDTO purchaseOrderItem : purchaseOrderItemList) {
                if (StrUtil.equals(purchaseOrderItem.getSkuId().toString(), lockStockResponse.getData().toString())) {
                    throw new LuckException("库存不足");
                }
            }
        }
        if (!lockStockResponse.isSuccess()) {
            throw new LuckException(lockStockResponse);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePurchaseOrderStatus(List<Long> purchaseOrderIds, Integer purchaseOrderStatus) {
        List<PurchaseOrderVO> purchaseOrderVOList = purchaseOrderMapper.listByPurchaseOrderIds(purchaseOrderIds);
        List<Long> purchaseOrderIdList = purchaseOrderVOList.stream().map(PurchaseOrderVO::getPurchaseOrderId).collect(Collectors.toList());
        purchaseOrderVOList.forEach(purchaseOrderVO -> {
            purchaseOrderVO.setStatus(purchaseOrderStatus);
            PurchaseOrder purchaseOrder = mapperFacade.map(purchaseOrderVO, PurchaseOrder.class);
            purchaseOrderMapper.updateByPurchaseId(purchaseOrder);
            // 还原库存
            reductionStock(purchaseOrderVO);
            updatePurchaseOrderStatus(purchaseOrder);
        });
        purchaseOrderItemMapper.updateStatusByPurchaseOrderId(purchaseOrderIdList, PurchasesStatusEnum.VOIDED.value());

    }

    /**
     * 处理导入的需要响应的信息
     *
     * @param errorMap 响应信息的集合
     * @return 响应信息
     */
    private String getUserExportInfo(Map<String, List<String>> errorMap) {
        StringBuilder info = new StringBuilder();
        List<String> importTotal = errorMap.get(PurchaseExcelListener.IMPORT_ROWS);
        BigDecimal total = new BigDecimal("0");
        if (CollUtil.isNotEmpty(importTotal)) {
            for (int i = 0; i < importTotal.size(); i++) {
                String item = importTotal.get(i);
                if (StrUtil.isNotBlank(item)) {
                    total = total.add(new BigDecimal(item));
                }
            }
        }
        info.append("共有： " + total.intValue() + "条数据成功导入" + StrUtil.LF);
        // 错误信息
        List<String> errorRows = errorMap.get(PurchaseExcelListener.ERROR_ROWS);
        if (CollUtil.isNotEmpty(errorRows)) {
            info.append("用户信息错误行数： " + Arrays.toString(errorRows.toArray()) + StrUtil.LF);
        }
        List<String> errors = errorMap.get(PurchaseExcelListener.OTHER);
        if (CollUtil.isNotEmpty(errors)) {
            for (String error : errors) {
                info.append(error);
            }
        }
        return info.toString();
    }
//
//    private void loadSupplierProdVO(Long supplierId, ExcelInfoVO excelInfoVO, Supplier supplier, List<String> errorList, List<String> partyCodeList, List<PurchaseProd> products) {
//        List<String> errorCodeList = new ArrayList<>();
//        List<SupplierProdVO> supplierProdList;
//        if (Objects.equals(supplier.getIsDefault(), 1)) {
//            supplierProdList = supplierProdService.listSupplierProdByPartyCodeList(partyCodeList);
//        } else {
//            supplierProdList = supplierProdService.listSupplierProd(supplierId);
//        }
//        Map<String, SupplierProdVO> map = supplierProdList.stream().collect(Collectors.toMap(SupplierProdVO::getPartyCode, p -> p));
//        Iterator<PurchaseProd> iterator = products.iterator();
//        while(iterator.hasNext()) {
//            PurchaseProd product = iterator.next();
//            // 不是默认供应商需要判断供应商下是否包含了该商品
//            if (Objects.equals(supplier.getIsDefault(), 0) && !map.containsKey(product.getPartyCode())) {
//                errorCodeList.add(product.getPartyCode());
//                iterator.remove();
//                continue;
//            } else if (!map.containsKey(product.getPartyCode())) {
//                continue;
//            }
//            SupplierProdVO supplierProdVO = map.get(product.getPartyCode());
//            product.setProdId(supplierProdVO.getProdId());
//            product.setProdName(supplierProdVO.getProdName());
//            product.setPic(supplierProdVO.getPic());
//            product.setSkuName(supplierProdVO.getSkuName());
//            product.setStocks(supplierProdVO.getStocks());
//            product.setSkuId(supplierProdVO.getSkuId());
//            if (Objects.equals(supplier.getIsDefault(), 1)) {
//                product.setMinOrderQuantity(1);
//                product.setSupplierProdId(0L);
//                product.setPurchasePrice(supplierProdVO.getPurchasePrice());
//                product.setSkuId(supplierProdVO.getSkuId());
//            } else {
//                product.setMinOrderQuantity(supplierProdVO.getMinOrderQuantity());
//                product.setSupplierProdId(supplierProdVO.getSupplierProdId());
//                if (product.getPurchasePrice() < supplierProdVO.getPurchasePrice()){
//                    product.setPurchasePrice(supplierProdVO.getPurchasePrice());
//                }
//                if (product.getPurchaseStock() <  supplierProdVO.getMinOrderQuantity()){
//                    product.setPurchaseStock(supplierProdVO.getMinOrderQuantity());
//                }
//            }
//        }
//        if (CollUtil.isNotEmpty(errorCodeList)) {
//            errorList.add(I18nMessage.getMessage("yami.purchases.order.error.code") + Constant.COLON + errorCodeList.toString());
//        }
//        if (CollUtil.isNotEmpty(products)) {
//            excelInfoVO.setData(Json.toJsonString(products));
//        }
//    }

    private StockBillLogItemVO loadStockBillLogItem(PurchaseOrderItemDTO purchaseOrderItemVO, Integer stock) {
        StockBillLogItemVO stockBillLogItem = new StockBillLogItemVO();
        stockBillLogItem.setStockCount(stock);
        stockBillLogItem.setUnitPrice(purchaseOrderItemVO.getPurchasePrice());
        stockBillLogItem.setSpuId(purchaseOrderItemVO.getSpuId());
        stockBillLogItem.setSkuId(purchaseOrderItemVO.getSkuId());
        stockBillLogItem.setCreateTime(new Date());
        stockBillLogItem.setUpdateTime(new Date());
        return stockBillLogItem;
    }

    private StockBillLogVO loadStockBillLog(PurchaseOrderVO purchaseOrderDb, List<StockBillLogItemVO> stockBillLogItems) {
        // 获取订单号
        ServerResponseEntity<Long> inStockResponse = segmentFeignClient.getSegmentId(DistributedIdKey.MALL4CLOUD_PRODUCT_STOCK_IN);
        if (!inStockResponse.isSuccess()) {
            throw new LuckException(inStockResponse.getMsg());
        }
        StockBillLogVO stockBillLog = new StockBillLogVO();
        stockBillLog.setSourceOrderNo(purchaseOrderDb.getPurchaseOrderId());
        stockBillLog.setStockBillType(StockBillType.PURCHASE_STORAGE.value());
        stockBillLog.setEmployeeId(purchaseOrderDb.getEmployeeId());
        stockBillLog.setBusinessTime(purchaseOrderDb.getDeliverTime());
        stockBillLog.setShopId(purchaseOrderDb.getShopId());
        stockBillLog.setRemark(purchaseOrderDb.getRemark());
        stockBillLog.setSupplierId(purchaseOrderDb.getSupplierId());
        stockBillLog.setType(StockType.WAREHOUSING.value());
        stockBillLog.setStatus(StockBillStatus.SUCCESS.value());
        stockBillLog.setStockBillNo(inStockResponse.getData().toString());
        long totalAmount = 0L;
        int totalCount = 0;
        for (StockBillLogItemVO stockBillLogItem : stockBillLogItems) {
            totalAmount = totalAmount + stockBillLogItem.getUnitPrice() * stockBillLogItem.getStockCount();
            totalCount += stockBillLogItem.getStockCount();
        }
        stockBillLog.setTotalAmount(totalAmount);
        stockBillLog.setTotalCount(totalCount);
        stockBillLog.setStockBillLogItems(stockBillLogItems);
        return stockBillLog;
    }

    /**
     * 订单语言信息处理
     *
     * @param purchaseOrder 订单
     */
    private void orderLangHandle(PurchaseOrderVO purchaseOrder) {
        Integer lang = I18nMessage.getLang();
        for (PurchaseOrderItemVO orderItem : purchaseOrder.getPurchaseOrderItemList()) {
            if (CollUtil.isEmpty(orderItem.getPurchaseOrderItemLangList())) {
                continue;
            }
            Map<Integer, PurchaseOrderItemLang> langMap = orderItem.getPurchaseOrderItemLangList().stream().collect(Collectors.toMap(PurchaseOrderItemLang::getLang, s -> s));
            PurchaseOrderItemLang orderItemLang;
            if (langMap.containsKey(lang)) {
                orderItemLang = langMap.get(lang);
            } else {
                orderItemLang = langMap.get(LanguageEnum.LANGUAGE_ZH_CN.getLang());
            }
            if (Objects.isNull(orderItemLang)) {
                continue;
            }
            orderItem.setSpuName(orderItemLang.getSpuName());
            orderItem.setSkuName(orderItemLang.getSkuName());
        }
    }
}
